<template>
  <div class="approval">
    <el-card class="box-card" style="margin-top: 110px;">
      <div class="title">{{$t('achievements.title1')}}</div>
      <div class="menu-search">
        <div class="menu-title">
          <!-- 渠道 -->
          <!-- <div class='searchItem'>
            <span>{{$t('productManage.channels')}}</span>
            <el-select v-model='listQuery.channel' size='small'>
                <el-option
                v-for='item in appChannel'
                :key='item.channel'
                :label='item.org_name'
                :value='item.channel'>
                </el-option>
            </el-select>
          </div> -->
          <!-- 状态 -->
          <div class='searchItem'>
            <span>{{$t('grouping.status')}}</span>
            <el-select v-model='listQuery.status' size='small'>
                <el-option
                v-for='item in statusArr'
                :key='item.value'
                :label='item.label'
                :value='item.value'>
                </el-option>
            </el-select>
          </div>
          <div class="menu-title-btn" style="margin-left: 20px;">
            <button type="button" @click="search">{{$t('btn.query')}}</button>
            <button type='button' @click='reset'>{{$t('btn.reset')}}</button>
          </div>
        </div>
      </div>
    </el-card>
    <el-card class="box-card" style="margin-top: 10px;margin-bottom: 20px;">
      <div style="display: flex; justify-content: space-between;">
        <div class="title">{{$t('product.productList')}}</div>
        <div style="color: red;line-height: 30px;">
          {{$t('product.levelConfigWarn')}}
        </div>
      </div>
      <el-form :rules="models.rules" :model="models" ref="form">
        <el-table
            v-loading="listLoading"
            ref="multipleTable"
            :data="models.tableData"
            tooltip-effect="dark"
            style="width: 100%; margin-top: 5px;"
            border
            size="mini"
        >
            <el-table-column :label="$t('user.num')" header-align="center" align="center" width="80">
            <template slot-scope="scope">
                <span>{{scope.row.index}}</span>
            </template>
            </el-table-column>
            <!-- 等级名称 -->
            <el-table-column
            header-align="center"
            align="center"
            prop="level"
            :label="$t('product.levelName')"
            width="500"
            ></el-table-column>
            <!-- 累计成功借款次数 -->
            <el-table-column
            header-align="center"
            align="center"
            :label="$t('product.addUpPayTime')"
            width="200"
            >
            <template slot-scope="scope">
                <div v-if="scope.row.attr1 === '0'" style="display: flex;justify-content: center;align-items: center;text-align: center;">
                  <div style="width: 30px; text-align: center;">{{scope.row.minPayTime}}</div>
                  <div style="width: 30px; text-align: center;">-</div>
                  <div style="width: 30px; text-align: center;">{{scope.row.maxPayTime}}</div>
                </div>
                <div v-if="scope.row.attr1 === '1'" style="display: flex;">
                    <el-col :span="11">
                        <el-form-item :prop="'tableData.' + scope.$index + '.minPayTime'" :rules='models.rules.minPayTime'>
                            <el-input size="mini" v-model="scope.row.minPayTime" :placeholder="$t('RiskManager.minVal')"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="2" style="display: flex; align-items: center; text-align: center; justify-content: center;">
                       <div>-</div>
                    </el-col>
                    <el-col :span="11">
                        <el-form-item :prop="'tableData.' + scope.$index + '.maxPayTime'" :rules='models.rules.maxPayTime'>
                            <el-input size="mini" v-model="scope.row.maxPayTime" :placeholder="$t('RiskManager.maxVal')"></el-input>
                        </el-form-item>
                    </el-col>
                </div>
            </template>
            </el-table-column>
            <!-- 状态 -->
            <el-table-column
            header-align="center"
            align="center"
            prop="status"
            width="260"
            :label="$t('grouping.status')"
            >
            <template slot-scope="scope">
              <el-radio-group v-model="scope.row.status" size="small" @change.native="changeStatus(scope.row, scope.$index)">
                <el-radio :label="1" size="mini">{{$t("grouping.enable")}}</el-radio>
                <el-radio :label="2" size="mini">{{$t("AppVersion.blockup")}}</el-radio>
              </el-radio-group>
            </template>
            </el-table-column>
            <el-table-column align="center" :label="$t('user.operation')" width="100" fixed="right">
            <template slot-scope="scope">
                <el-button v-if="scope.row.attr1 === '0'" size="small" type="text" @click="handleUpdate(scope.row)">{{$t('btn.edit')}}
                    </el-button>
                <el-button v-if="scope.row.attr1 === '1'" size="small" type="text" @click="handleSave(scope.row)" style="color: #67c23a;">{{$t('btn.conserve')}}
                    </el-button>
            </template>
            </el-table-column>
        </el-table>
      </el-form>
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="listQuery.page"
          :page-sizes="[10, 30, 50]"
          :page-size="listQuery.limit"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        ></el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import { getChannels } from 'api/customQuery/index';
import {
  loanLevelPage,
  updateStatus,
  updateLoanLevel,
  updateLevelFlag
} from "api/product/userGradeConfig/index";
export default {
  data() {
    return {
      isDis: true,
      levelArr: [
        {
          id: null,
          level: this.$t("rule.all")
        }
      ],
      appChannel: [],
      statusArr: [
        {
          value: '',
          label: this.$t("rule.all")
        },
        {
          value: 1,
          label: this.$t("grouping.enable")
        },
        {
          value: 2,
          label: this.$t("AppVersion.blockup")
        }
      ],
      listLoading: false,
      total: null,
      listQuery: {
        limit: 10,
        page: 1,
        status: ''
      },
      isBatch: false,
      models: { 
        rules: {
          minPayTime: [
            { required: true, message: this.$t('RiskManager.minVal')}
          ],
          maxPayTime: [
            { required: true, message: this.$t('RiskManager.maxVal')}
          ],
        },
        tableData: [
            {
                level: '',
                maxPayTime: '',//右值
                minPayTime: '',//左值
                status: 1, // 1启用2停用
            }
        ],
      }
    };
  },
  computed: {
    ...mapGetters(["elements", "userGradeConfigPage"])
  },
  created() {
    if (this.userGradeConfigPage.has(this.$route.path)) {
      this.listQuery = this.userGradeConfigPage.get(this.$route.path);
    }
    // 渠道下拉
    // getChannels().then(res => {
    //   this.appChannel = res.data;
    //   this.listQuery.channel = this.appChannel[0].channel;
    // });
    this.getList();
  },
  methods: {
    // 点击编辑按钮
    handleUpdate(row) {
      let obj = {};
      obj.id = row.id;
      obj.flag = '1';
      updateLevelFlag(obj)
      .then( res => {
        if (res.status === 200) {
          this.getList();
        }
      })
    },
    // 点击保存按钮
    handleSave(row) {
      if (row.minPayTime === '' || row.minPayTime === undefined || row.minPayTime === null) {
        this.$message({
          showClose: true,
          type: "warning",
          message: this.$t('RiskManager.inpThresholdMin')
        });
      } else if (row.maxPayTime === '' || row.maxPayTime === undefined || row.maxPayTime === null) {
        this.$message({
          showClose: true,
          type: "warning",
          message: this.$t('RiskManager.inpThresholdMax')
        });
      } else {
        this.$confirm(this.$t('orderDivision.isSave'), {
          confirmButtonText: this.$t('btn.confirm'),
          cancelButtonText: this.$t('btn.cancel'),
          type: "warning",
          center: true
        })
        .then(() => {
          let formObj = {};
          // formObj.channel = this.listQuery.channel;
          // formObj.level = row.level;
          formObj.id = row.id;
          formObj.minPayTime = row.minPayTime;
          formObj.maxPayTime = row.maxPayTime;
          updateLoanLevel(formObj)
          .then( res => {
            if (res.status === 200) {
              let obj = {};
              obj.id = row.id;
              obj.flag = '0';
              updateLevelFlag(obj)
              .then( response => {
                if (response.status === 200) {
                  this.getList();
                  this.$message({
                    showClose: true,
                    type: "success",
                    message: this.$t("group.savesuccess")
                  });
                }
              })
            }
          })
        })
        .catch(() => {
          this.$message({
            showClose: true,
            type: "info",
            message: this.$t('approvalDetail.cue3')
          });
        });
      }
    },
    changeStatus(row, currentIndex) {
      let lastIndex = currentIndex - 1; // 上一等级
      let nextIndex = parseInt(currentIndex) + 1; // 下一等级
      let len = this.models.tableData.length;
      if (row.status === 1) { // 点击启用
        if (lastIndex === -1) {
          let obj = {};
          // obj.channel = this.listQuery.channel;
          // obj.level = row.level;
          obj.id = row.id;
          obj.status = row.status;
          updateStatus(obj).then(res => {
            if (res.status === 200) {
              this.$message({
                showClose: true,
                type: "success",
                message: this.$t("approvalDispatch.opersuccess")
              });
              this.getList();
            } else {
              this.$message({
                showClose: true,
                type: "warning",
                message: res.message
              });
              this.getList();
            }
          });
        } else if (lastIndex !== -1) {
          this.models.tableData.forEach((item, index) => {
            if (lastIndex === index) { // 判断上一级是否存在
              if (item.status === 2) { // 若上一级未启用，给出提示
                this.$message({
                  showClose: true,
                  type: "warning",
                  message: this.$t('product.clickEnable')
                });
                row.status = 2;
              } else {
                let obj = {};
                // obj.channel = this.listQuery.channel;
                // obj.level = row.level;
                obj.id = row.id;
                obj.status = row.status;
                updateStatus(obj).then(res => {
                  if (res.status === 200) {
                    this.$message({
                      showClose: true,
                      type: "success",
                      message: this.$t("approvalDispatch.opersuccess")
                    });
                    this.getList();
                  } else {
                    this.$message({
                      showClose: true,
                      type: "warning",
                      message: res.message
                    });
                    this.getList();
                  }
                }); 
              }
            }
          })
        }
      } else if (row.status === 2) { // 点击禁用
        if (nextIndex === len) {
          let obj = {};
          // obj.channel = this.listQuery.channel;
          // obj.level = row.level;
          obj.id = row.id;
          obj.status = row.status;
          updateStatus(obj).then(res => {
            if (res.status === 200) {
              this.$message({
                showClose: true,
                type: "success",
                message: this.$t("approvalDispatch.opersuccess")
              });
              this.getList();
            } else {
              this.$message({
                showClose: true,
                type: "warning",
                message: res.message
              });
            }
          }); 
        } else if (nextIndex !== len) {
          this.models.tableData.forEach((item, index) => {
            if (nextIndex === index) { // 判断下一级是否存在
              if (item.status === 1) { // 若下一级未禁用，给出提示
                this.$message({
                  showClose: true,
                  type: "warning",
                  message: this.$t('product.clickProhibit')
                });
                row.status = 1;
              } else {
                let obj = {};
                // obj.channel = this.listQuery.channel;
                // obj.level = row.level;
                obj.id = row.id;
                obj.status = row.status;
                updateStatus(obj).then(res => {
                  if (res.status === 200) {
                    this.$message({
                      showClose: true,
                      type: "success",
                      message: this.$t("approvalDispatch.opersuccess")
                    });
                    this.getList();
                  } else {
                    this.$message({
                      showClose: true,
                      type: "warning",
                      message: res.message
                    });
                  }
                }); 
              }
            }
          })
        }
      }
    },
    getList() {
      this.listLoading = true;
      this.$store.dispatch("saveUserGradeConfigPage", {
        path: this.$route.path,
        listQuery: this.listQuery
      });
      loanLevelPage(this.listQuery).then(res => {
        res.data.rows.forEach((item, index) => {
          item.index =
            index + (this.listQuery.page - 1) * this.listQuery.limit + 1;
        });
        this.models.tableData = res.data.rows;
        this.listLoading = false;
        this.total = Number(res.data.total);
      });
    },
    //查询
    search() {
      this.listQuery.page = 1;
      this.getList();
    },
    //重置
    reset() {
      this.listQuery.limit = 10;
      this.listQuery.page = 1;
      this.listQuery.status = '';
    },
    handleSizeChange(val) {
      this.listQuery.limit = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.listQuery.page = val;
      this.getList();
    }
  }
};
</script>

<style scoped lang='scss'>
.box-card {
  width: 95%;
  margin-left: 2.5%;
  margin-right: 2.5%;
}
.title {
  line-height: 30px;
  font-size: 16px;
  display: flex;
  align-items: center;
  font-weight: bold;
}
.title:before {
  display: block;
  content: "";
  width: 3px;
  height: 16px;
  background-color: #309afe;
}
.title:before {
  margin-right: 8px;
}
::before {
  box-sizing: inherit;
  -webkit-tap-highlight-color: transparent;
}
.menu-title {
  width: 100%;
  box-sizing: border-box;
  background: #ffffff;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  .searchItem {
    display: flex;
    align-items: center;
    padding: 10px 0;
    span {
      display: inline-block;
      width: 100px;
      text-align: right;
      font-size: 12px;
      color: #5f5f61;
      padding-right: 5px;
    }
    div:nth-child(2) {
      width: 150px;
    }
  }
  .searchItem-date {
    display: flex;
    align-items: center;
    padding: 10px 0;
    b {
      margin: 0 10px;
      font-weight: normal;
      font-size: 12px;
      color: #5f5f61;
    }
    div {
      width: 150px;
    }
  }
}
.menu-title-btn {
  padding: 10px 0;
  box-sizing: border-box;
  button {
    padding: 0 20px;
    height: 28px;
    background: #20a0ff;
    color: #fff;
    outline: none;
    border-width: 0;
    border-radius: 4px;
    font-size: 12px;
    margin-left: 10px;
    &:nth-child(1) {
      margin-left: 0;
    }
    &:nth-child(2) {
      background: #ebf5ff;
      color: #20a0ff;
      border: 1px solid #abd5ff;
    }
  }
  button[disabled] {
    padding: 0 20px;
    height: 28px;
    background: #c1e0ff;
    color: #fafbff;
    outline: none;
    border-width: 0;
    border-radius: 4px;
    font-size: 12px;
  }
}
.menu-list {
  padding: 20px 0;
  box-sizing: border-box;
  button {
    padding: 0 20px;
    height: 28px;
    background: #20a0ff;
    color: #fff;
    outline: none;
    border-width: 0;
    border-radius: 4px;
    font-size: 12px;
    margin-left: 10px;
    &:nth-child(1) {
      margin-left: 0;
    }
  }
  button[disabled] {
    padding: 0 20px;
    height: 28px;
    background: #c1e0ff;
    color: #fafbff;
    outline: none;
    border-width: 0;
    border-radius: 4px;
    font-size: 12px;
  }
}
.box-card /deep/.el-form-item {
    margin-bottom: 1px;
}
</style>